<?php

namespace app\api\controller\order;

use app\api\controller\Api;
use app\common\audit\logic\AuditResultLogic;
use app\common\order\model\Order;
use app\common\order\model\OrderAdditional;
use app\common\order\model\OrderIncome;
use app\common\order\model\OrderProduct;
use app\common\order\model\OrderProtocol;
use app\common\order\validate\OrderIncomeValidate;
use app\common\order\validate\OrderProductValidate;
use app\common\order\validate\OrderProtocolValidate;
use app\common\system\model\OperateLog;
use Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class Product extends Api
{

    public function getList()
    {
        $post = $this->request->post();

        // 服务内容
        $orderProductModel = new OrderProduct();
        $list = $orderProductModel->where('order_id', $post['order_id'])->select();

        // 主服务内容
        $products = [];
        $changed = [
            1 => [
                'times' => 0,
                'amount' => 0,
                'total' => 0,
            ],
            2 => [
                'times' => 0,
                'amount' => 0,
                'total' => 0,
            ],
            3 => [
                'times' => 0,
                'amount' => 0,
                'total' => 0,
            ],
            4 => [
                'times' => 0,
                'amount' => 0,
                'total' => 0,
            ],
        ];
        foreach ($list as $row) {
            if ($row['type'] == 0) {
                $row->append(['category', 'company', 'banquet', 'product', 'user', 'check_tag']);
                array_push($products, $row);
            } else {
                $index = $row['type'];
                $changed[$index] = [
                    'times' => $changed[$index]['times'] + 1,
                    'amount' => $changed[$index]['amount'] + $row['amount'],
                    'total' => round($changed[$index]['total'] + $row['total'], 2),
                ];
            }
        }
        $result['products'] = $products;
        $result['changed'] = $changed;

        // 获取增项
        $additionalModel = new OrderAdditional();
        $additional = $additionalModel->where('order_id', $post['order_id'])->where('type', 0)->select();
        foreach ($additional as $row) {
            $row->append(['company', 'category', 'product', 'user', 'check_tag']);
        }
        $result['additional'] = $additional;

        return success($result);
    }

    public function getTypeList()
    {
        $post = $this->request->post();
        if(empty($post['order_id']) || empty($post['type'])) return error([], '参数错误');

        $orderProductModel = new OrderProduct();
        $where = [];
        $where['order_id'] = $post['order_id'];
        $where['type'] = $post['type'];
        $list = $orderProductModel->where($where)->select();
        foreach ($list as $row) {
            $row->append(['category', 'company', 'type_tag', 'user', 'check_tag']);
        }

        $result['list'] = $list;

        return success($result, "获取数据成功");
    }

    public function create()
    {
        $post = $this->request->post();
        $user = $this->request->user;


        $product = $post['OrderProduct'];
        if (empty($product['order_id'])) return error([], "参数错误");

        $orderModel = new Order();
        $order = $orderModel->where('id', $product['order_id'])->find();

        $where = [];
        $where[] = ['order_id', '=', $product['order_id']];
        $where[] = ['type', '=', '0'];
        // StoreCategory
        $hasWhere = [];
        $hasWhere[] = ['order_model', 'in', ['Banquet', 'Meeting', 'Baby']];
        $masterProduct = OrderProduct::hasWhere('StoreCategory', $hasWhere)->where($where)->find();
        if (empty($masterProduct)) return error([], "数据异常");

        $product['company_id'] = $masterProduct['company_id'];
        $product['category_id'] = $masterProduct['category_id'];
        $protocol['user_id'] = $user['id'];
        $orderProductValidate = new OrderProductValidate();
        if (!$orderProductValidate->check($product)) {
            return error([], $orderProductValidate->getError());
        }

        // 酒店协议
        $protocol = $post['OrderProtocol'];
        $protocol['company_id'] = $masterProduct['company_id'];
        $protocol['category_id'] = $masterProduct['category_id'];
        $protocol['user_id'] = $user['id'];
        $protocolValidate = new OrderProtocolValidate();
        if (!$protocolValidate->check($protocol)) {
            return error([], $protocolValidate->getError());
        }

        $updateType = $product['type'];
        if ($updateType != 2 && $updateType != 4) {
            // 收款
            $income = $post['OrderIncome'];
            $incomeValidate = new OrderIncomeValidate();
            if (!$incomeValidate->check($income)) {
                return error([], $incomeValidate->getError());
            }
        }

        $source = [];
        $modelName = OrderProduct::class;
        $model = new OrderProduct();
        $model->startTrans();
        $row['user_id'] = $user['id'];
        try {
            $model->save($product);
            $source[$modelName][] = $model->id;
        } catch (DbException $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }

        // 添加酒店协议
        $modelName = OrderProtocol::class;
        $protocolModel = new OrderProtocol();
        $protocol['user_id'] = $user['id'];
        try {
            $protocolModel->save($protocol);
            $source[$modelName] = $protocolModel->id;

        } catch (DbException $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }

        if ($updateType != 2 && $updateType != 4) {
            // 收款信息
            $modelName = OrderIncome::class;
            $income['user_id'] = $user['id'];
            $incomeModel = new OrderIncome();
            try {
                $incomeModel->save($income);
                $source[$modelName] = $incomeModel->id;
            } catch (DbException $e) {
                $model->rollback();
                return error([], $e->getMessage());
            }
        }

        $auditRsLogic = new AuditResultLogic();
        $master = $order->getData();
        $options = [
            'company_id' => $master['company_id'],
            'timing' => 'table'
        ];

        try {
            $auditNo = $auditRsLogic->initAudit($master, $user, $source, $options);
            foreach ($source as $className => $row) {
                try {
                    $where = [];
                    if (is_array($row)) {
                        $where[] = ['id', 'in', $row];
                    } else {
                        $where[] = ['id', '=', $row];
                    }
                    $class = new $className;
                    $class->where($where)->save(['check_no' => $auditNo]);
                } catch (DbException $e) {
                    return error([], $e->getMessage());
                }
            }
            $model->commit();

            return success([], '操作成功');
        } catch (Exception $e) {
            $msg = $e->getMessage();
        } catch (DbException $e) {
            $msg = $e->getMessage();
        }
        return error([], $msg, 404);
    }

    public function save()
    {
        $post = $this->request->post();
        $user = $this->request->user;


        $product = $post['OrderProduct'];
        if (empty($product['order_id'])) return error([], "参数错误");

        $orderModel = new Order();
        $order = $orderModel->where('id', $product['order_id'])->find();

        $where = [];
        $where[] = ['order_id', '=', $product['order_id']];
        $where[] = ['type', '=', '0'];
        // StoreCategory
        $hasWhere = [];
        $hasWhere[] = ['order_model', 'in', ['Banquet', 'Meeting', 'Baby']];
        $masterProduct = OrderProduct::hasWhere('hasWhere', $hasWhere)->where($where)->find();
        if (empty($masterProduct)) return error([], "数据异常");

        $product['company_id'] = $masterProduct['company_id'];
        $product['category_id'] = $masterProduct['category_id'];
        $protocol['user_id'] = $user['id'];
        $orderProductValidate = new OrderProductValidate();
        if (!$orderProductValidate->check($product)) {
            return error([], $orderProductValidate->getError());
        }

        // 酒店协议
        $protocol = $post['OrderProtocol'];
        $protocol['company_id'] = $masterProduct['company_id'];
        $protocol['category_id'] = $masterProduct['category_id'];
        $protocol['user_id'] = $user['id'];
        $protocolValidate = new OrderProtocolValidate();
        if (!$protocolValidate->check($protocol)) {
            return error([], $protocolValidate->getError());
        }
        $updateType = $product['type'];
        if ($updateType != 2 && $updateType != 4) {
            // 收款
            $income = $post['OrderIncome'];
            $incomeValidate = new OrderIncomeValidate();
            if (!$incomeValidate->check($income)) {
                return error([], $incomeValidate->getError());
            }
        }

        $source = [];
        $modelName = OrderProduct::class;
        $model = new OrderProduct();
        $model->startTrans();
        $row['user_id'] = $user['id'];
        try {
            $productRow = $model->where('id', $product['id'])->find();
            $productRow->save($product);
            $source[$modelName][] = $product['id'];
        } catch (DbException $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }

        // 添加酒店协议
        $modelName = OrderProtocol::class;
        $protocolModel = new OrderProtocol();
        $protocol['user_id'] = $user['id'];
        try {
            $protocolRow = $protocolModel->where('id', $protocol['id'])->find();
            $protocolRow->save($protocol);
            $source[$modelName] = $protocol['id'];

        } catch (DbException $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }

        if ($updateType != 2 && $updateType != 4) {
            // 收款信息
            $modelName = OrderIncome::class;
            $income['user_id'] = $user['id'];
            $incomeModel = new OrderIncome();
            try {
                $incomeRow = $incomeModel->where('id', $income['id'])->find();
                $incomeRow->save($income);
                $source[$modelName] = $income['id'];
            } catch (DbException $e) {
                $model->rollback();
                return error([], $e->getMessage());
            }
        }

        $auditRsLogic = new AuditResultLogic();
        $master = $order->getData();
        $options = [
            'company_id' => $master['company_id'],
            'timing' => 'table'
        ];
        try {
            $auditNo = $auditRsLogic->initAudit($master, $user, $source, $options);
            foreach ($source as $className => $row) {
                try {
                    $where = [];
                    if (is_array($row)) {
                        $where[] = ['id', 'in', $row];
                    } else {
                        $where[] = ['id', '=', $row];
                    }
                    $class = new $className;
                    $class->where($where)->save(['check_no' => $auditNo]);
                } catch (DbException $e) {
                    return error([], $e->getMessage());
                }
            }
            $model->commit();

            return success([], '操作成功');
        } catch (Exception $e) {
            $msg = $e->getMessage();
        } catch (DbException $e) {
            $msg = $e->getMessage();
        }
        return error([], $msg, 404);
    }

    public function update()
    {
        $post = $this->request->post();
        $user = $this->request->user;

        $orderProductValidate = new OrderProductValidate();
        if (!$orderProductValidate->check($post)) {
            return error([], $orderProductValidate->getError());
        }

        $model = new OrderProduct();
        try {
            $row = $model->where('id', $post['id'])->find();
        } catch (DataNotFoundException $e) {
            return error([], '数据已不存在');
        }

        $model->startTrans();
        try {
            $post['user_id'] = $user['id'];
            $origin = $row->getData();
            $row->save($post);

            $changed = $row->getData();
            $modelName = OrderAdditional::class;
            OperateLog::write($user['id'], $post['order_id'], $origin, $changed, $modelName);
        } catch (DbException $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }
        $model->commit();

        return success([], '更新成功');
    }
}